package com.honey.solr.daosupport.method;

import java.util.List;

import com.honey.compilation.java.IfBlock;
import com.honey.compilation.java.JavaVisibility;
import com.honey.compilation.java.Method;
import com.honey.compilation.java.MethodDecoration;
import com.honey.compilation.java.Parameter;
import com.honey.generator.java.AbstractClassName;
import com.honey.solr.SchemaField;
import com.honey.solr.SolrFactory;

public class SetQueryParameterMethod extends AbstractClassName {
	

	private SolrFactory solrFactory = null;
	
	public SetQueryParameterMethod(SolrFactory solrFactory ){
		this.solrFactory =solrFactory;
	}
	public Method createMethod(){
		Method answer =new Method("addQueryParameter");
		
		MethodDecoration d = answer.getDecoration();
		d.setFinal(true);
		d.setVisibility(JavaVisibility.PRIVATE);
		
		Parameter parameter = new Parameter("SolrQuery","query");
		answer.addParameter(parameter);
		
		boolean bool = solrFactory.getSolrPlugin().getQueryForPage() != null ;
		
		answer.addBodyLine("query.setHighlight(this.highlight)");
		answer.addBodyLine("query.setHighlightSimplePre(this.highlightSimplePre)");
		answer.addBodyLine("query.setHighlightSimplePost(this.highlightSimplePost)");
		
		List<SchemaField> list = solrFactory.getSchemaFields();
		for(SchemaField sf : list ){
			//if(sf.isStored() && sf.isRequired() &&( sf.getType().isText() || sf.getType().isString() ))
			if( sf.getType().isText() || sf.getType().isString() )
			answer.addBodyLine("query.addHighlightField(\""+sf.getName()+"\")");
		}
		
		if(bool){	
			parameter = new Parameter(solrFactory.getSolrPlugin().getQueryForPage(),"page");
			answer.addParameter(parameter) ;
			
			IfBlock block = new IfBlock("page != null");
			block.addBodyLine("query.setStart(page.getBegin())");
			block.addBodyLine("query.setRows(page.getInterval())");
			block.addBodyLine("if( page.getOrderBy() != null ){");
			block.addBodyLine("query.addSortField( page.getSort(), page.getDir() ==  Page.Dir.ASC ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc )");
			block.addBodyLine("}");
			answer.addBlocks(block);
		}
		
		return answer;
	}
}
